<template>
  <div >
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-s-promotion"></i> 订单管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品订单</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <div>

      <template>
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="全部订单" name="first"></el-tab-pane>
          <el-tab-pane label="待付款" name="second"></el-tab-pane>
          <el-tab-pane label="待发货" name="third"></el-tab-pane>
          <el-tab-pane label="已发货" name="fourth"></el-tab-pane>
          <el-tab-pane label="已完成" name="five"></el-tab-pane>
          <el-tab-pane label="已关闭" name="six"></el-tab-pane>
          <el-tab-pane label="已取消" name="seven"></el-tab-pane>
        </el-tabs>
      </template>





<!--      订单编号-->
      <br>
      <el-col >
        <el-col :span="9">
          <template>
            <div class="block">
              <el-date-picker
                  v-model="timeRange"
                  @change="sendTimeRange"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetimerange"
                  align="left"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :default-time="['12:00:00', '08:00:00']">
              </el-date-picker>
            </div>
          </template>
        </el-col>
        <el-col  :span="6">
          <el-input
              placeholder="请输入用户名搜索"
              v-model="input" @keyup.enter.native="selectByName">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-col>
        <el-col :span="9" >
          <el-button type="warning" @click="selectByName">查询</el-button>
          <el-button style="margin-left: 200px" @click="exportExcelSelect">导出Excel</el-button>
<!--          <el-button style="margin-left: 20px" @click="exportAllData">导出全部数据</el-button>-->
        </el-col>
      </el-col>


      <template>
        <el-table
            :data="tableData"
            @selection-change="handleSelectionChange">
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="供货商姓名" prop="userName" align="center"></el-table-column>
          <el-table-column label="供货商电话" prop="userPhone" align="center"></el-table-column>
          <el-table-column label="订单编号" prop="orderId" align="center"></el-table-column>
          <el-table-column label="下单时间" prop="submitTime"  align="center"></el-table-column>
          <el-table-column label="订单金额" prop="orderAmount" align="center"></el-table-column>
          <el-table-column label="订单状态" prop="orderStatus" align="center" :data="orderList">
            <template slot-scope="scope">
              {{ getOrderStatusText(scope.row.orderStatus) }}
            </template>
          </el-table-column>
          <el-table-column
              align="right">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  @click="handleEdit(scope.row)">查看订单</el-button>
              <el-button
                  size="mini"
                  type="danger"
                  @click="open(scope.row)">删除订单</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--预览弹窗表格-->
        <el-dialog title="表格保存预览" width="70%" :visible.sync="selectWindow">
        <el-table
            :data="selectData"
            height="380px"
            id="selectTable">
          <el-table-column label="供货商姓名" prop="userName" align="center"></el-table-column>
          <el-table-column label="供货商电话" prop="userPhone" align="center"></el-table-column>
          <el-table-column label="订单编号" prop="orderId" align="center"></el-table-column>
          <el-table-column label="下单时间" prop="submitTime" align="center"></el-table-column>
          <el-table-column label="订单金额" prop="orderAmount" align="center"></el-table-column>
          <el-table-column label="订单状态" prop="orderStatus" align="center" :data="orderList" >
            <template slot-scope="scope">
              {{ getOrderStatusText(scope.row.orderStatus) }}
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="exportExcel">确定保存</el-button>
        </div>
        </el-dialog>
      </template>

      <template>

        <div class="block">
          <br>
          <el-pagination
              @current-change="changePage"
              :page-size="pageSize"
              hide-on-single-page
              layout="total,  prev, pager, next, jumper"
              :current-page="currentPage"
              :total="total">
          </el-pagination>
        </div>
      </template>

    </div>

  </div>
</template>


<script>
import moment from "moment";
import axios from "axios";import FileSaver from "file-saver";
import XLSX from "xlsx";
// import * as XLSX from 'xlsx/xlsx.mjs';


export default {
  data() {
    return {
      orderList: [
        { orderStatus: 0 },
        { orderStatus: 1 },
        { orderStatus: 2 },
        { orderStatus: 3 },
        { orderStatus: 4},
        { orderStatus: 5},
        // 其他订单数据...
      ],
      input:'',
      total:0,
      pageSize:0,
      currentPage: 0,
      //全部订单行
      activeName: 'first',

      baseUrl:'http://localhost:29182//hotel/order',
      tableData: [],
      //表格中选中的数据
      selectData: [],
      selectWindow: false,
      allDataSelected: false,
      timeRange: [], // 新增的属性，用于保存时间区间
      search: '',
      value1: '',
    };
  },
  methods: {
    //订单状态改变绑定
    getOrderStatusText(status) {
      if (status === 1) {
        return '待发货';
      } else if (status === 2) {
        return '已发货';
      } else if (status === 3) {
        return '已完成';
      } else if (status === 4) {
        return '已关闭';
      }else if (status === 5) {
        return '已取消';
      } else {
        return '待付款';
      }
      // 其他状态...
    },
    handlePayClick(){
      this.$router.push('http://localhost:19001/alipay/order')
    },
    //  通过用户名搜索订单  搜索功能
    selectByName(){
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }
      let url = this.baseUrl+'/selectgoodsbyname?name=' + this.input+'&page='+page;
      console.log('url = ' + url);
      axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
          console.log("跳转成功");
        }
      });
    },



    //  时间查询方法
    sendTimeRange() {
      console.log("DATE:" + this.timeRange)
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }
      let url = this.baseUrl+'/selectOrderByTime?page=' + page;

      console.log('url = ' + url);

      // 发送请求到后端
      this.axios.post(url, this.timeRange).then(response => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });

    },


    // 加载商品列表
    loadGoodsList(orderStatus) {
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }

      let url = this.baseUrl+'/selectGoodsOrder?orderStatus=' + orderStatus + '&page=' + page;

      console.log('url = ' + url);

      axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    //导出全部数据  excel
    exportAllData() {
      if (this.tableData.length < 1) {
        this.$message.error('没有数据可导出！');
        return false;
      }
      if (this.allDataSelected) {
        this.selectData = this.tableData;
      } else {
        this.selectData = [];
      }
      this.selectWindow = true;
    },

    //格式化数据
    getExcel(dom, title = '默认标题',) {
      var excelTitle = title;
      var wb = XLSX.utils.table_to_book(document.querySelector(dom));
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, { bookType: "xlsx", bookSST: true, type: "array" });
      try {
        FileSaver.saveAs(
            new Blob([wbout], { type: "application/octet-stream" }),
            excelTitle + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },

    //导出
    exportExcel() {
      this.getExcel('#selectTable', '导出的自定义标题')
    },
    //显示预览弹窗
    exportExcelSelect() {
      if (this.selectData.length < 1) {
        this.$message.error('请选择要导出的内容！');
        return false;
      }
      if (this.selectData.length === this.tableData.length) {
        this.allDataSelected = true;
      } else {
        this.allDataSelected = false;
      }
      this.selectWindow = true;
    },

    //选中数据
    handleSelectionChange(val) {
      this.selectData = val;
    },
    //  日期转换格式
 /*   formatDate(row, column) {
      /!* const date = new Date(row.checkInDate);
    return new Date(date).toLocaleString('en-CN', {timeZone: 'Asia/Shanghai'});*!/
      return moment(row.date).utcOffset(8).format('YYYY-MM-DD HH:mm:ss');
    },*/

    changePage(page) {
      //todo 需要在订单界面添加用户信息的字段
// todo  userid需要根据实际情况修改
      this.$router.replace('?&page=' + page);
      let orderStatus = 0;
      switch (this.activeName) {
        case 'first':
          orderStatus = 6
          break;
        case 'second':
          orderStatus = 0
          break;
        case 'third':
          orderStatus = 1
          break;
        case 'fourth':
          orderStatus = 2
          break;
        case 'five':
          orderStatus = 3
          break;
        case 'six':
          orderStatus = 4
          break;
        case 'seven':
          orderStatus = 5
          break;


        default:
          break;
      }
      this.loadGoodsList(orderStatus);
    },
    handleClick(tab) {
      if (tab.label == "全部订单") {
        this.loadGoodsList(6);
      }
      if (tab.label === "待付款") {
        this.loadGoodsList(0);
      }
      if (tab.label === "待发货") {
        this.loadGoodsList(1);
      }
      if (tab.label === "已发货") {
        this.loadGoodsList(2);
      }
      if (tab.label === "已完成") {
        this.loadGoodsList(3);
      }
      if (tab.label === "已关闭") {
        this.loadGoodsList(4);
      }
      if (tab.label === "已取消") {
        this.loadGoodsList(5);
      }
    },
    handleEdit(order) {
      // 使用路由跳转到另一个页面
      this.handleselect(order);
      // 使用路由跳转到另一个页面
      if (order.orderStatus===0){
        this.$router.push({ path: '/admin/order/goodsorderdetail/start', query: { order: JSON.stringify(order) } });
      };
      if (order.orderStatus===1){
        this.$router.push({ path: '/admin/order/goodsorderdetail/tobesend', query: { order: JSON.stringify(order) } });
      };
      if (order.orderStatus===2){
        this.$router.push({ path: '/admin/order/goodsorderdetail/sended', query: { order: JSON.stringify(order) } });
      };
      if (order.orderStatus===3){
        this.$router.push({ path: '/admin/order/goodsorderdetail/finish', query: { order: JSON.stringify(order) } });
      };
      if (order.orderStatus===4){
        this.$router.push({ path: '/admin/order/goodsorderdetail/close', query: { order: JSON.stringify(order) } });
      };
      if (order.orderStatus===5){
        this.$router.push({ path: '/admin/order/goodsorderdetail/cancel', query: { order: JSON.stringify(order) } });
      };
    },
    //通过id查询订单

    handleselect(order){
      let url = this.baseUrl+'/selectGoodsOrder/' + order.id;
      console.log('url = ' + url);
      axios.get(url).then((response) => {
        let orderdetail='';
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          orderdetail=jsonResult.data;
          console.log("跳转成功");
        }
      });
    },

    // 删除操作
    open(order) {
      let message = '此操作将永久删除\"' + order.userName + '\"是否继续?'
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(order);
      })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
    },
    // 执行删除
    handleDelete(order) {
      // let url = BaseUrl.ADMIN_MALL + '/goods/' + goods.id + '/delete';
      let url = this.baseUrl+'/deletegoods/' + order.id;
      console.log('url = ' + url);
      axios.post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          let orderStatus = 0;
          switch (this.activeName) {
            case 'first':
              orderStatus = 6
              break;
            case 'second':
              orderStatus = 0
              break;
            case 'third':
              orderStatus = 1
              break;
            case 'fourth':
              orderStatus = 2
              break;
            case 'five':
              orderStatus = 3
              break;
            case 'six':
              orderStatus = 4
              break;
            case 'seven':
              orderStatus = 5
              break;

            default:
              break;
          }
          this.loadGoodsList(orderStatus);
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadGoodsList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    }
  },
  mounted() {
     this.loadGoodsList(6);
  }

};
</script>
